﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

using Common;
using System.Web;
namespace Session_Server.Controllers
{
    /// <summary>
    /// 单点登录，接口封装
    /// </summary>
    [EnableCors("*", "*", "*")]
    public class LoginController : BaseController
    {
        /// <summary>
        /// 获取当前Session的ID
        /// </summary>
        /// <returns></returns>
        [EnableCors("*", "*", "*", SupportsCredentials = true)]
        public string GetSessionID()
        {
            return _Session.SessionID;
        }

        LogHelper.LogHelper _log = new LogHelper.LogHelper();
        /// <summary>
        /// 判断当前回话的用户是否已经登录
        /// </summary>
        /// <returns></returns>
        public string GetLogin(string sessionid)
        {
            //1.获取所有Session内容
            foreach (var item in _Application.AllKeys)
            {
                if (item == sessionid)
                {
                    AccountInfo acount = _Application[item.ToString()] as AccountInfo;
                    if (acount != null && acount.SessionID == sessionid)
                    {
                        return acount.ToJsonString();
                    }
                }
            }
            return "0";
        }
        /// <summary>
        /// 判断处理用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string CheckUser()
        {
            string token = ReqHelper.GetString("token");
            string username = ReqHelper.GetString("username");
            string pwd = ReqHelper.GetString("pwd");
            if (pwd == "123")
            {
                //登录成功，返回cookie的值
                _Application.Add(token, new AccountInfo()
                {
                    UserName = username,
                    SessionID = token
                });
                return $"username={username}&sessionid={token}";
            }
            return "0";
        }
        /// <summary>
        /// 登录用户信息
        /// </summary>
        public class AccountInfo
        {
            public string UserName { get; set; }
            public string SessionID { get; set; }
        }
    }
}
